package com.xiaoyu.izf.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.xiaoyu.izf.aspect.RequestAuth;
import com.xiaoyu.izf.model.MerchantInfo;
import com.xiaoyu.izf.model.Region;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.Vocation;
import com.xiaoyu.izf.model.page.DataTableBean;
import com.xiaoyu.izf.model.page.FormResultBean;
import com.xiaoyu.izf.model.page.ParamListBean;
import com.xiaoyu.izf.model.page.Status;
import com.xiaoyu.izf.service.MerchantInfoService;
import com.xiaoyu.izf.service.RegionService;
import com.xiaoyu.izf.service.VocationService;
import com.xiaoyu.izf.util.CommonUtil;
import com.xiaoyu.izf.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * 商户
 */
@Controller
@RequestMapping("/merchant")
public class MerchantInfoController extends BaseController{

    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private RegionService regionService;
    @Autowired
    private VocationService vocationService;

    /**
     * 商户列表-合伙人
     * @param request
     * @return
     */
    @RequestMapping("/par_list_page")
    @RequestAuth
    public String parListPage(HttpServletRequest request, Model model){
        UserInfo user = user(request);
        model.addAttribute("user",user);
        return "mgr/merchant/par_list";
    }
    @RequestMapping("/par_list")
    @ResponseBody
    @RequestAuth
    public DataTableBean parList(HttpServletRequest request, @RequestBody String body) throws IOException {
        UserInfo user = user(request);
        ParamListBean paramListBean = getParamListBean(body);
        DataTableBean dataTableBean = merchantInfoService.list(paramListBean,user);
        return dataTableBean;
    }

    /**
     * 商户列表-admin
     * @param request
     * @return
     */
    @RequestMapping("/list_page")
    @RequestAuth
    public String listPage(HttpServletRequest request, Model model){
        UserInfo user = user(request);
        model.addAttribute("user",user);
        return "mgr/merchant/list";
    }
    @RequestMapping("/list")
    @ResponseBody
    @RequestAuth
    public DataTableBean list(HttpServletRequest request, @RequestBody String body) throws IOException {
        UserInfo user = user(request);
        ParamListBean paramListBean = getParamListBean(body);
        DataTableBean dataTableBean = merchantInfoService.list(paramListBean,user);
        return dataTableBean;
    }

    /**
     * 商户添加
     * @param request
     * @return
     */
    @RequestMapping("/add_page")
    @RequestAuth
    public String addPage(HttpServletRequest request,Model model,Integer uid){
        if (uid==null){
            uid = user(request).getId();
        }
        List<Region> provinces = regionService.provinces();
        List<Vocation> merchantTypes = vocationService.merchantTypes();
        String today = DateTimeUtil.getDate2Str();
        String timeFrame = today.substring(0,8)+"01至"+today;
        model.addAttribute("timeFrame",timeFrame);
        model.addAttribute("provinces",provinces);
        model.addAttribute("merchantTypes",merchantTypes);
        model.addAttribute("uid",uid);
        return "mgr/merchant/add";
    }
    @RequestMapping("/add")
    @ResponseBody
    @RequestAuth
    public FormResultBean add(HttpServletRequest request,MerchantInfo merchant,
                                      int provinceRegionId,int cityRegionId,int countyRegionId,
                                      String detailAddress,int merchantTypeId,int firstVocationId,
                                      int secondVocationId,int uid,String idnumberTime,String licencenumberTime) {
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());
        if (!Validator.isMobile(merchant.getLinkmanMobile())){
            return fr.setType("error").setMessage("手机号格式不正确");
        }
        if (merchantInfoService.findByLinkmanMobile(merchant.getLinkmanMobile())!=null){
            return fr.setType("error").setMessage("联系人手机号已存在");
        }
        if (!Validator.isEmail(merchant.getEmail())){
            return fr.setType("error").setMessage("请输入正确邮箱格式");
        }
        if (!(Validator.isMobile(merchant.getServicePhone())||CommonUtil.isPhone(merchant.getServicePhone()))){
            return fr.setType("error").setMessage("手机号或座机号格式不正确");
        }
        if (merchantInfoService.findByName(merchant.getMerchantName())!=null){
            return fr.setType("error").setMessage("商户名称已存在");
        }
        if (merchantInfoService.findBySimpleName(merchant.getMerchantSimpleName())!=null){
            return fr.setType("error").setMessage("商户简称已存在");
        }

        Vocation merchantType = vocationService.findById(merchantTypeId);
        Vocation firstVocation = vocationService.findById(firstVocationId);
        Vocation secondVocation = vocationService.findById(secondVocationId);
        if (merchantType==null){
            return fr.setType("error").setMessage("请选择商户类别");
        }
        if (firstVocation==null){
            return fr.setType("error").setMessage("请选择一级行业");
        }
        String merchantTypeInfo = merchantType.getVocationName()+"--"+firstVocation.getVocationName();
        if (secondVocation!=null)
            merchantTypeInfo += "--"+secondVocation.getVocationName();
        merchant.setMerchantTypeInfo(merchantTypeInfo);

        Region province = regionService.findByRegionId(provinceRegionId);
        Region city = regionService.findByRegionId(cityRegionId);
        Region county = regionService.findByRegionId(countyRegionId);
        if (province==null){
            return fr.setType("error").setMessage("请选择省份");
        }
        if (city==null){
            return fr.setType("error").setMessage("请选择城市");
        }
        String merchantAddress = province.getRegionName()+"--"+city.getRegionName();
        if (county!=null){
            merchantAddress += "--"+county.getRegionName();
            merchant.setRegionCode(county.getRegionCode());
        }else {
            merchant.setRegionCode(city.getRegionCode());
        }
        merchantAddress += "--"+detailAddress;
        merchant.setMerchantAddress(merchantAddress);

        String[] idnumberTimes = idnumberTime.split("至");
        String[] licencenumberTimes = licencenumberTime.split("至");
        merchant.setLegalPersonIdNumberStart(DateUtil.parseDate(idnumberTimes[0]).toSqlDate());
        merchant.setLegalPersonIdNumberEnd(DateUtil.parseDate(idnumberTimes[1]).toSqlDate());
        merchant.setBusinessLicenseStart(DateUtil.parseDate(licencenumberTimes[0]).toSqlDate());
        merchant.setBusinessLicenseEnd(DateUtil.parseDate(licencenumberTimes[1]).toSqlDate());

        merchantInfoService.add(merchant,uid);

        return fr.setType("success").setMessage("添加成功");
    }


    @RequestMapping("/rate_set_page")
    @RequestAuth
    public String rateSetPage(int merchantId,Model model){
        MerchantInfo merchantInfo = merchantInfoService.findById(merchantId);
        model.addAttribute("merchantId",merchantId);
        model.addAttribute("merchantInfo",merchantInfo);
        return "mgr/merchant/rate_set";
    }
    @RequestMapping("/rate_set")
    @ResponseBody
    @RequestAuth
    public FormResultBean rateSet(int merchantId,double rateReturnCommission){
        System.err.println(merchantId);
        System.err.println(rateReturnCommission);
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());

        MerchantInfo merchantInfo = merchantInfoService.findById(merchantId);
        if (merchantInfo==null){
            return fr.setType("error").setMessage("商户不存在");
        }
        merchantInfo.setRateReturnCommission(rateReturnCommission);
        merchantInfoService.save(merchantInfo);

        return fr.setType("success").setMessage("操作成功");
    }
}
